package com.gpj.security.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @className WebSecurityConfig
 * @description
 *   TODO
 * @author GPJ
 * @date 2023/11/7 22:14
 * @version 1.0
 **/
@Configuration
//@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
	// 密码编码器
	@Bean
	public PasswordEncoder passwordEncoder(){
		return NoOpPasswordEncoder.getInstance();
	}

	/**
	 * 安全拦截机制
	 */
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests()
				.antMatchers("/login").permitAll() // /login放行
				.antMatchers("/login-success").permitAll() // /login放行
				.anyRequest().permitAll() // 剩余认证拦截
				.and().formLogin() // 允许表单登录(不允许表单登录,则认证拦截后验证失败会直接报403)
//				.loginPage("/login-g") // 自定义登录页地址
				.successForwardUrl("/login-success") // 登录成功跳转地址
		;

	}

















	//定义用户信息服务（查询用户信息）
/*
    @Bean
    public UserDetailsService userDetailsService(){
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(User.withUsername("zhangsan").password("123").authorities("p1").build());
        manager.createUser(User.withUsername("lisi").password("456").authorities("p2").build());
        return manager;
    }
*/

	//密码编码器
    /*@Bean
    public PasswordEncoder passwordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }*/
//	@Bean
//	public PasswordEncoder passwordEncoder() {
//		return new BCryptPasswordEncoder();
//	}

	//安全拦截机制（最重要）
	/*@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.csrf().disable()
				.authorizeRequests()
//                .antMatchers("/r/r1").hasAuthority("p2")
//                .antMatchers("/r/r2").hasAuthority("p2")
				.antMatchers("/r/**").authenticated()//所有/r/**的请求必须认证通过
				.anyRequest().permitAll()//除了/r/**，其它的请求可以访问
				.and()
				.formLogin()//允许表单登录
				.loginPage("/login-view")//登录页面
				.loginProcessingUrl("/login")
				.successForwardUrl("/login-success")//自定义登录成功的页面地址
				.and()
				.sessionManagement()
				.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
				.and()
				.logout()
				.logoutUrl("/logout")
				.logoutSuccessUrl("/login-view?logout");
	}*/
}